package com.zsr.service.impl;

import com.zsr.dao.BookDao;
import com.zsr.dao.impl.BookDaoImpl;
import com.zsr.pojo.Book;
import com.zsr.pojo.Page;
import com.zsr.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService  {

    private BookDao bookDao =new BookDaoImpl();

    @Override
    public void addBook(Book book) {
        bookDao.addBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
        bookDao.deleteBookById(id);
    }

    @Override
    public void updateBook(Book book) {
        bookDao.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return bookDao.queryBookById(id);
    }

    @Override
    public List<Book> queryBooks() {
        return bookDao.queryBooks();
    }

    /**
     * 返回分页模型
     * @param pageNo 当前页
     * @param pageSize 每页数据量
     * @return
     */
    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page=new Page<>();
        page.setPageSize(pageSize);

        Integer pageTotalCount =bookDao.queryForPageTotalCount();
        //求总记录数
        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal =pageTotalCount / pageSize;
        pageTotal = pageTotalCount % pageSize >0 ? pageTotal+1: pageTotal;
        //求总页码
        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);


        //当前页开始数据的索引= (当前页码 - 1) * 每页数据
        int begin =(page.getPageNo() - 1) * pageSize;
        //求每页显示数据
        List<Book> items =bookDao.queryForPageItems(begin,pageSize);
        page.setItems(items);

        return page;
    }

    @Override
    public Page<Book> pageByPrice(int pageNo, int pageSize, int min, int max) {
        Page<Book> page=new Page<>();
        page.setPageSize(pageSize);

        //求总记录数
        Integer pageTotalCount =bookDao.queryForPageTotalCount(min,max);
        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal =pageTotalCount / pageSize;
        pageTotal = pageTotalCount % pageSize >0 ? pageTotal+1: pageTotal;
        //求总页码
        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);


        //当前页开始数据的索引= (当前页码 - 1) * 每页数据
        int begin =(page.getPageNo() - 1) * pageSize;
        //求每页显示数据
        List<Book> items =bookDao.queryForPageItems(begin,pageSize,min,max);
        page.setItems(items);

        return page;
    }
}
